<?php
class Debug{
    
    
    public function __construct(){
    }
    
    //捕获系统致命错误
    public static function shutDown(){
        $e = error_get_last();
        switch ($e['type']) {
            case 1:
                self::appError($e['type'], $e['message'], $e['file'], $e['line']);
                break;
        }
    }
    
    //错误处理
    public static function appError($err_no = 0, $err_msg = '', $err_file = '', $err_line = 0){
        $log = array(
            '['.date('Y-m-d h:i:s').']',
            '|',
            $err_no,
            '|',
            $err_msg,
            '|',
            $err_file,
            '|',
            $err_line
        );
        self::saveLog(implode(' ',$log)."\r\n",'error');
    }
    
    //异常处理器（捕获所有throw抛出的异常）
    public static function Exception($e){
        $log=array(
            '['.date('Y-m-d h:i:s').']',
            '['.get_client_ip(0,true).']',
            '[http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].']',
            '['.M_NAME.'/'.C_NAME.'/'.A_NAME.']',
            '['.$e->getMessage().']['.$e->getFile().']['.$e->getLine().']'
        );
        $ex_log=implode('',$log);
        if(DEBUG)  exit($ex_log);//调试模式直接输出
        else self::saveLog($ex_log."\r\n",'exception');//记录日志
        $code=$e->getCode();
        switch($code){
           case 404:
              send_http_status(404);
              if(IS_AJAX) exit(json_encode(array('status'=>'y','info'=>'错误代码：404')));
              else include SITE_PATH.'404.html';
              break;
           default:
              if(IS_AJAX) exit(json_encode(array('status'=>'y','info'=>'系统异常')));
              else include SITE_PATH.'404.html';
              break;
            }
        exit;
    }
    
    public static function saveLog($msg,$type){
        $path=SITE_PATH.'log/'.$type.'/'.date('Ym').'/';
        if (!is_dir($path)) {
            mkdir($path,0777,true);
        }
        $filename = $path . '/' . date('Ymd') . '.log';
        file_put_contents($filename,$msg."\r\n", FILE_APPEND);
    }
    
}